package com.slj.spring_security_demo.config;


import com.slj.spring_security_demo.entity.RoleEntity;
import com.slj.spring_security_demo.entity.UserEntity;
import com.slj.spring_security_demo.repository.UserRepository;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


public class DBUserDetailsManager implements UserDetailsManager, UserDetailsPasswordService {

    @Resource
    private UserRepository userRepository;

    @Override
    public UserDetails updatePassword(UserDetails user, String newPassword) {
        return null;
    }

    @Override
    public void createUser(UserDetails user) {
        UserEntity userEntity = new UserEntity();
        userEntity.setName(user.getUsername());
        userEntity.setPassword(user.getPassword());
        userEntity.setEnabled(true);
        userRepository.save(userEntity);
    }

    @Override
    public void updateUser(UserDetails user) {

    }

    @Override
    public void deleteUser(String username) {

    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {

    }

    @Override
    public boolean userExists(String username) {
        return false;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserEntity userEntity = userRepository.findByName(username);
        if (Objects.nonNull(userEntity)) {
            User.UserBuilder build = User.withUsername(userEntity.getName())
                    .disabled(false)
                    .accountExpired(false)
                    .accountLocked(false)
                    .password(userEntity.getPassword());
            if (!CollectionUtils.isEmpty(userEntity.getRoles())) {
                List<String> roles = new ArrayList<>();
                List<String> privileges = new ArrayList<>();
                for (RoleEntity role : userEntity.getRoles()) {
                    roles.add(role.getName());
                    if (!CollectionUtils.isEmpty(role.getPrivileges())) {
                        privileges.addAll(role.getPrivileges().stream().map(p -> p.getName()).collect(Collectors.toList()));
                    }
                }
                build.roles(roles.toArray(String[]::new));
                build.authorities(privileges.toArray(String[]::new));
            }
            return build.build();
        }
        return null;
    }
}
